<?php

namespace app\modules\Finance\controllers;

use Yii;
use app\modules\Finance\models\Finance;
use app\modules\Finance\models\FinanceSearch;
use app\modules\Finance\models\FinanceOrder;
use app\modules\Finance\models\FinanceImg;
use app\modules\Product\models\Product;
use app\modules\Product\models\ProductSearch;
use app\modules\Order\models\Order;
use app\modules\Order\models\OrderSearch;
use app\modules\Finance\models\FinanceCompany;
use app\modules\Finance\models\ReceiveAccount;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\filters\AccessControl;
use yii\data\Pagination;
use yii\data\ArrayDataProvider;

/**
 * FinanceController implements the CRUD actions for Finance model.
 */
class FinanceController extends Controller
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
		return [
			'verbs' => [
				'class' => VerbFilter::className(),
				'actions' => [
					'delete' => ['post'],
				],
			],
			'access' => [
				'class' => AccessControl::className(),
				'rules' => [
					[
						'allow' => true,
						'roles' => ['@'],
					],
				],
			],
		];
	}


	/**
	   按步骤添加财务单
	 */
	public function actionStep1(){
		$model = new Finance();

		$model->type = 1;
        return $this->render('step1', [ 'model' => $model ]);
	}

    /**
     * Lists all Finance models.
     * @return mixed
     */
    public function actionIndex(){//{{{

        $searchModel = new FinanceSearch();
        $dataProvider = $searchModel->search_all(Yii::$app->request->queryParams);
       
        $min_price = $max_price = 0;
        if(isset(Yii::$app->request->queryParams['FinanceSearch']['min_price'])){
        	$min_price = Yii::$app->request->queryParams['FinanceSearch']['min_price'];
        }
        if(isset(Yii::$app->request->queryParams['FinanceSearch']['max_price'])){
        	$max_price = Yii::$app->request->queryParams['FinanceSearch']['max_price'];
        }

        $all_model = [];
        
        if($dataProvider){
        	foreach($dataProvider as $model){
        		if($min_price == 0 && $max_price == 0){
        			$all_model[] = $model;
        		}else if($min_price != 0 && $max_price == 0){
        			if($model->orderPrice >= $min_price){
        				$all_model[] = $model;
        			}
        		}else if($min_price == 0 && $max_price != 0){
        			if($model->orderPrice <= $max_price){
        				$all_model[] = $model;
        			}
        		}else if($min_price !=0 && $max_price !=0){

        			if($model->orderPrice >= $min_price && $model->orderPrice <= $max_price){
        				$all_model[] = $model;
        			}
        		}
        	}
        }

        //sort 创建时间排序 
        $sort = 0;
        if(isset(Yii::$app->request->queryParams['FinanceSearch']['sort'])){
        	$sort = Yii::$app->request->queryParams['FinanceSearch']['sort'];
        }

        if($sort == 1){
        	$sort = SORT_ASC;
        }else{
        	$sort = SORT_DESC;
        }

        $provider = new ArrayDataProvider([
              'allModels' => $all_model,
              'sort' => [
			        'attributes' => ['created_at'],
			        'defaultOrder' => [
			        	'created_at' => $sort,
			        ],
			   ],
              'pagination' => [
                  'pageSize' => 20,
                  'defaultPageSize'=>20,
              ],
        ]);

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $provider,
            'min_price' => $min_price,
            'max_price' => $max_price
        ]);
    }//}}}

    /**
     * Displays a single Finance model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id){ //{{{
		$model = $this->findModel($id);

		if($model->status == 4 || $model->status ==5 ){ // 操作驳回  财务驳回
			// 判断是否是自己申请的审批
			if($model->user_id == yii::$app->user->id){
				// 重新提交审批页面	
        		return $this->render('again', [
        		    'model' => $model,
        		]);
			}
		}

        return $this->render('view', [
            'model' => $model,
        ]);
    }//}}}

	// 再次提交审批
	public function actionAgainSubmit($id){
		
		$model = $this->findModel($id);

		if($model->status == 4 || $model->status ==5 ){ // 操作驳回  财务驳回

			$model->status = 1;
			if($model->save()){

        		return $this->redirect(['view', 'id' => $model->id]);
			}
		}

	}

    /**
     * Creates a new Finance model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate(){//{{{
        $model = new Finance();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['view', 'id' => $model->id]);
        } else {
			$model->type = 1;
			$model->price_type = 1;
			$model->is_invoice = 1;

            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }//}}}

	/**
	 * 从订单直接发起创建
	 * params	order_id 	INT
	 * 
	 */
    public function actionQuickCreate($order_id){//{{{
		$order = Order::findOne($order_id);

        $model = new Finance();

		$model->type = 1;
		$model->price_type = 1;
		$model->is_invoice = 1;

        return $this->render('quick_create', ['model' => $model, 'order'=>$order] );
    }//}}}

    public function actionQuickCreateSave(){//{{{
		$params = Yii::$app->request->post();

		$model = new Finance();

		if( $model->load($params) && $model->save() ){
			
			$order = Order::findOne($params['order_id']);

			$finance_order = new FinanceOrder();

			$finance_order->finance_id = $model->id;
			$finance_order->order_id = $order->id;
			$finance_order->order_code = $order->code;
			$finance_order->product_id = $order->product_id;
			$finance_order->product_code = $order->product->code;

			// 默认金额   获取订单已提交审批的金额
			$p = $order->financeAllPrice; // 已提交及审批通过的金额
			$p1 = $order->price - $p;	
			$finance_order->price = ($p1 <0 ) ? 0 : $p1;

			$finance_order->save();
		}

        return $this->redirect(['view', 'id' => $model->id]);
    }//}}}

	// 修改关联单金额
	public function actionEditPrice($id){//{{{
		$params = yii::$app->request->get();

		if(isset($params['Order']['price']) ){

			$model = FinanceOrder::findOne($params['id']);
			$model->price = $params['Order']['price'];

			if($model->save()){
				$finance = Finance::findOne($model->finance_id);
				print_r(json_encode(['output'=>$model->price, 'total'=>Yii::$app->formatter->asCurrency($finance->orderPrice), 'message'=>"" ]));
			}
		}
	}//}}}
	
	/* 选择关联订单 */
	public function actionOrder($id){//{{{
		
        $params  = Yii::$app->request->get();
		$model = $this->findModel($id); // Finance Model

		// 获取所有未过期团期
		$start = date("Y-m-d", strtotime("-6 month"));  // date('Y-m-d');
		$field = "product.id, product.go_time, product.return_time, product.name, product.code";

		$query = Product::find();
		$query->select($field)->where(['>=', 'product.go_time', $start])->orderBy('product.go_time');
		$query->andWhere(['product.status'=>1]);
		$query->andWhere(['>', 'order.id', 0]); // 只获取有订单的船期

        $query->joinWith(['payOrderAll']);   // FinanceModel -> getPayOrderAll()

		$query->andWhere(['!=', 'order.status', 4]);	

		$productModel = new ProductSearch();
		$orderModel = new OrderSearch();
		if(isset($params['ProductSearch'])){
			if(isset($params['ProductSearch']['cruise_id']) && !empty($params['ProductSearch']['cruise_id'])){
				$query->andWhere(['product.cruise_id'=>$params['ProductSearch']['cruise_id']]);
			}
			//if(isset($params['ProductSearch']['code']) && !empty($params['ProductSearch']['code'])){
			//	$query->andWhere(['like', 'product.code', $params['ProductSearch']['code']]);
			//}
			
			$productModel->load($params);
		}

		if(isset($params['OrderSearch'])){
			if(isset($params['OrderSearch']['code']) && !empty($params['OrderSearch']['code'])){
				$params['OrderSearch']['code'] = trim($params['OrderSearch']['code']);
				$query->andWhere(['order.code' => $params['OrderSearch']['code']]);	
			}
			
			if(isset($params['OrderSearch']['username']) && !empty($params['OrderSearch']['username'])){
				$params['OrderSearch']['username'] = trim($params['OrderSearch']['username']);
				$query->andWhere(['order.username' => $params['OrderSearch']['username']]);	
			}
			$orderModel->load($params);
		}

		// 去除重复数据
		$query->groupBy("product.id");
		
		$pages = new Pagination(['totalCount' =>$query->count(), 'pageSize' => 10]);
		$product = $query->offset($pages->offset)->limit($pages->limit)->all(); // 

		// 判断是新增, 还是已经添加过关联的审批
		$orders = $model->order;

        return $this->render('order', [
            'model' => $model,
            'product' => $product,
            'orders' => $orders,
            'pages' => $pages,
            'productModel' => $productModel, //	new Product(),
            'orderModel' => $orderModel, //	new Order(),
        ]);
	}//}}}

	/* 保存关联订单 */
	public function actionFinanceOrder(){//{{{
		
        $params  = Yii::$app->request->post();

		$finance_id = isset($params['finance_id']) ? $params['finance_id'] : NULL;
		$price = isset($params['price']) ? $params['price'] : [];
		$order_id = isset($params['order_id']) ? $params['order_id'] : [];

		if(!empty($finance_id) && !empty($price) && !empty($order_id)){
			
			$data = array_combine($order_id, $price);
			
			foreach($data as $key=>$val){
				$order = Order::findOne($key);
				$model = new FinanceOrder();

				$model->finance_id = $finance_id;
				$model->order_id = $key;
				$model->order_code = $order->code;
				$model->product_id = $order->product_id;
				$model->product_code = $order->product->code;
				$model->price = $val;
				
				$model->save();
			}
		}

        return $this->redirect(['view', 'id' => $finance_id]);
	}//}}}

	/** 审核 */
	public function actionFinanceCheck($id){//{{{

        $model = $this->findModel($id);

        $params  = Yii::$app->request->post();

		//if(!empty($params)){
		if($model->load($params)){
			
		}else{
            return $this->render('check', ['model' => $model,]);
		}
	}//}}}

	/** 移除订单 */
	public function actionRemoveOrder($id){//{{{
		// 判断当前审批的状态 是否可以做修改  是否已经开具发票

		$model = FinanceOrder::findOne($id);
		
		if($model){
			$finance_id = $model->finance_id;
			$model->delete();

            return $this->redirect(['view', 'id' => $finance_id]);
		}
	}//}}}

	/** 移除照片 */
	public function actionRemoveImg($id){//{{{
		// 判断删除的条件
		$model = FinanceImg::findOne($id);
				
		if($model){
			$finance_id = $model->finance_id;
			$model->delete();

            return $this->redirect(['view', 'id' => $finance_id]);
		}
	}//}}}

	// 根据订单获取相关审批详情
	public function actionOrderDetail($order_id){//{{{
		$this->layout = false;
		$query = FinanceOrder::find();

		$query->where(['order_id'=>$order_id]);

		$data = $query->all();

		$order = Order::findOne($order_id);

	    return $this->render('order-detail', [
        	    'data' => $data,
        	    'order' => $order,
        ]);
	}//}}}


    /**
     * Updates an existing Finance model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $this->redirect(['order', 'id' => $model->id]);
            //return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }
	
	// 修改
    public function actionEdit($id){ //{{{

		\Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

        $model = $this->findModel($id);

		$params = Yii::$app->request->get();

        if ($model->load($params) && $model->save()) {

			$param = $params['Finance'];
			$key = array_keys($param);
			$k = $key[0];

			if($k == 'price_type'){
				
				$data = Yii::$app->params['finance_price_type'][$model->price_type];
			}elseif($k == 'type'){

				$data = Yii::$app->params['finance_type'][$model->type];
			}elseif($k == 'is_invoice'){
				$data = Yii::$app->params['is_invoice'][$model->is_invoice];
			}else{
				$data = $model->$k;
			}

			return ['output'=>$data, 'message'=>"" ];
        }
    }//}}}
	
	/** 审批状态变更 */
    public function actionStatus(){//{{{

		$id = Yii::$app->request->post('id');
		$status  = Yii::$app->request->post('status');

        if ($id && $status) {

        	$model = $this->findModel($id);

			$model->status = $status;
			$model->save();

			// 审批通过 修改订单状态
			if($status == 3){

				Yii::$app->orderblock->status($model);
			}
			// 记录审批记录

            return $this->redirect(['finance-check', 'id' => $model->id]);
        }
    }//}}}

	public function actionSuggest($q = null){//{{{
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
		
		$out = $arr = [];

		if($q){

			$data = FinanceCompany::find()->where(['like', 'company', $q])->all();
			if($data){
				foreach($data as $key=>$model){
					
					$arr[$key] = ['id'=>$model->id, 'text'=>sprintf("%s (%s | %s)", $model->company, $model->name, $model->account) ]; 			
				}
			}
		}

		if($arr){
			$out['results'] = $arr;
			return $out;
		}else{
			$arr[] = ['id'=>'' , 'text'=>'无结果'];	
			$out['results'] = $arr;
			return $out;
			//return NULL; 
		}
	}//}}}

	public function actionFindCompany($id = null){//{{{
		Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;

		if($id){
			$model = FinanceCompany::findOne($id);
		
			return $model;
		}
	}//}}}


	//获取收款账号
	public function actionGetAccount(){
		$data = yii::$app->request->get();
		$out = [];
		if(isset($data['type_id'])){

			$arr = ReceiveAccount::find()->where(['type'=>$data['type_id']])->all();

            if($arr){
                foreach($arr as $key=>$v){
                    $out[$key]['id'] = $v->account;
                    $out[$key]['name'] = $v->account;
                    $out[$key]['remark'] = $v->remark;
                }
            }
            echo json_encode(['output'=>$out, 'selected'=>'']);
            return ;
		}
		echo json_encode(['output'=>'', 'selected'=>'']);
    }

	/**
	 *	应收账款变更为收款单 
	 * 
	 */
	public function actionEditType($id){//{{{
	
        $model = $this->findModel($id);

		if($model->type == 2){
			$model->type = 1;
			$ret = $model->save();
			//Yii::$app->logs->message($id, $type); // type=3
		}
	
        return $this->redirect(['finance-check', 'id' => $model->id]);
	}//}}}


	// 打印收据 发票
	public function actionPrint($id){//{{{

        $model = $this->findModel($id);

	    return $this->render('print', ['model' => $model]);
	}//}}}


    /**
     * Deletes an existing Finance model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the Finance model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return Finance the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = Finance::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
